package com.ys.controller.api.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.base.TbUserTaxManage;
import com.ys.entity.sys.YsCol;
import com.ys.service.base.TbUserTaxManageService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 员工个税管理
 */
@Controller
@RequestMapping("/api/inter/tbUserTaxManage")
public class ApiInterTbUserTaxManageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbUserTaxManageController.class);

    @Autowired
    private CommonApiService<TbUserTaxManage> commonApiService;

    @Autowired
    private TbUserTaxManageService tbUserTaxManageService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TbUserTaxManage setSeachSql(TbUserTaxManage cond){
        cond.addField("R.GearNo AS gearNo");
        cond.addField("R.YearTaxMin AS yearTaxMin");
        cond.addField("R.YearTaxMax AS yearTaxMax");
        cond.addField("R.TaxRate AS taxRate");
        cond.addField("R.DeductNum AS deductNum");
        //cond.addField("A.YearTaxMin + '＜X≤' + A.YearTaxMax AS yearTaxMinAndMax");
        cond.addLeftJoin("TB_UserTaxRate R ON R.TaxManageId = A.Id AND 1=1");
        //排序
        cond.setOrderby("A.UpdateTime DESC");
        cond = commonApiService.dataAuth(MenuId.TB_UserTaxRate, cond);
        return  cond;
    }

    //处理返回的数据
    public List setList(List<Map<String, Object>> resDate){
        List<Map<String, Object>> tableDate = new ArrayList();
        resDate.forEach(item->{
            if(item.get("yearTaxMin")!=null && item.get("yearTaxMax")!=null){
                item.put("yearTaxMinAndMax",item.get("yearTaxMin") + "＜X≤" + item.get("yearTaxMax"));
            }
            tableDate.add(item);
        });
        return tableDate;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tbUserTaxManage:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TbUserTaxManage cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            //获取
            JSONArray tableVoJAData = tableVoJA.getData();
            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));

            //处理数据
            resList = setList(resListNew);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
            tableVoJA.setData(jsonArray);

            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }



    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbUserTaxManage cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TB_UserTaxRate)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            listData = setList(listData);

            //处理数据
            ExportExcelUtils<TbUserTaxManage> util = new ExportExcelUtils<>(new TbUserTaxManage());
            String toFilePath = util.exportExcel(listData, listField, "员工个税管理");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 保存
     */
    @RequestMapping("/toSave")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tbUserTaxManageService.save(params,MenuId.TB_UserTaxManage,MenuId.TB_UserTaxRate,MenuId.TB_UserTaxManageItem);
        } catch (Exception e) {
            logger.error("保存出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 删除员工个税税率表
     */
    @RequestMapping("/toDelTaxRate")
    @ResponseBody
    public R toDelRecord(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            for(int i=0;i<idList.size();i++) {
                //删除
                tbUserTaxManageService.toDelTaxRate(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        }catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 删除员工个税管理子表
     */
    @RequestMapping("/toDelItem")
    @ResponseBody
    public R toDelItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            for(int i=0;i<idList.size();i++) {
                //删除
                tbUserTaxManageService.toDelItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        }catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


}